package com.bdqn.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bdqn.common.HttpUtils;
import com.bdqn.pojo.Account;
import com.bdqn.pojo.SocialUser;
import com.bdqn.service.AccountService;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;


/**
 * Gitee登录处理
 */
@Controller
public class AccessTokenController {

    @Autowired
    AccountService accountService;

    @GetMapping("home/home/index")
    public String index(@RequestParam(name = "code") String code,
                        @RequestParam(name = "code") String state, HttpServletRequest request) throws Exception {
        Map<String,String> map =new HashMap<>();
        map.put("client_id","aa34c72d530caef7b9614064ae9f5499585fc79055c32bb01b7631bb497f9b32");
        map.put("client_secret","6c399c983a3016a8c99bd0a275b6e9643b6e7523fbb9687946a01748362f8765");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://localhost:8080/home/home/index");
        map.put("code",code);


        //1、根据code换取accessToken
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(),map,new HashMap<>());
        //2、处理
        if (response.getStatusLine().getStatusCode()==200) {
            //获取到了accessToken
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);


            // 登录和注册合并逻辑
            Map<String, String> map1 = new HashMap<>();
            System.out.println(socialUser.getAccess_token());
            map1.put("access_token", socialUser.getAccess_token());
            // 通过access_token获取用户的信息（ID、昵称等）
            HttpResponse response1 = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<>(), map1);

            StringBuffer sbUrl = new StringBuffer("https://gitee.com/api/v5/user");
            if (null != map1) {
                StringBuilder sbQuery = new StringBuilder();
                for (Map.Entry<String, String> query : map1.entrySet()) {
                    if (0 < sbQuery.length()) {
                        sbQuery.append("&");
                    }
                    if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
                        sbQuery.append(query.getValue());
                    }
                    if (!StringUtils.isBlank(query.getKey())) {
                        sbQuery.append(query.getKey());
                        if (!StringUtils.isBlank(query.getValue())) {
                            sbQuery.append("=");
                            sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                        }
                    }
                }
                if (0 < sbQuery.length()) {
                    sbUrl.append("?").append(sbQuery);
                }
            }
            HttpRequest httpRequest = HttpUtil.createGet(sbUrl.toString());
            cn.hutool.http.HttpResponse responseUser = httpRequest.execute();

            String json1 = null;
            if (responseUser.isOk()) {
                json1 = responseUser.body();
            }

            if (json1 != null) {

//            if (response1.getStatusLine().getStatusCode() == 200) {
//                String json1 = EntityUtils.toString(response1.getEntity());
                System.out.println("=================="+json1);
                JSONObject jsonObject = JSON.parseObject(json1);
                String id = jsonObject.getString("id");
                Long idId = Long.parseLong(id);
                String name = jsonObject.getString("name");
                System.out.println(id);
                System.out.println(name);
                //把数据添加到数据库中
                Account account = new Account();
                account.setId(idId);
                account.setName(name);
                int idA=accountService.add(account,1);
                System.out.println("==="+idA);
                request.getSession().setAttribute("account", account);
                System.out.println("account:"+request.getSession().getAttribute("account"));
                if (idA > 0){
                    System.out.println("成功");
                }

            } else {
                return "redirect:http://localhost:8080/home/login2";
            }
        }
        //2、登录成功就会跳到首页
        return "redirect:http://localhost:8080/home/index";
    }
}
